<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="dataParent"
      :page="page"
      ref="crud"
      v-model="formParent"
      :permission="permissionList"
      :before-open="beforeOpen"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @row-click="handleRowClick"
    >
      <template #menu-left>
        <el-button
          type="danger"
          v-if="permission.dict_delete"
          plain
          @click="handleDelete"
          >删除
        </el-button>
        <el-button
          type="primary"
          v-if="permission.dict_delete"
          @click="handleImport"
          >导 入
        </el-button>
      </template>
      <template #menu-right>
        <el-button
          type="danger"
          v-if="permission.dict_delete"
          plain
          @click="handleDelete"
          >删除
        </el-button>
      </template>
      <template #menu="scope">
        <el-dropdown popper-class="avue-crud-more">
          <span class="el-dropdown-link-tab">
            更 多
            <el-icon class="el-icon--right">
              <more-filled />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>操作一</el-dropdown-item>
              <el-dropdown-item>操作二</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
      <template #code="{ row }">
        <el-tag @click="handleRowClick(row)" style="cursor: pointer">{{ row.code }}</el-tag>
      </template>
      <template #isSealed="{ row }">
        <el-tag type="warning">{{ row.isSealed === 0 ? '否' : '是' }}</el-tag>
      </template>
    </avue-crud>
    <el-dialog title="导入" append-to-body v-model="excelBox" width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
        <template #excelTemplate>
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getParentList,
  remove,
  update,
  add,
  getDict,
} from '@/api/system/dict';
import { option } from '@/option/system/avue-crud';
import { mapGetters } from 'vuex';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';

export default {
  data() {
    return {
      dictValue: '暂无',
      parentId: -1,
      formParent: {
        imgUrl:["/images/logo-bg.jpg",'https://www.w3school.com.cn/i/movie.ogg','https://www.runoob.com/try/demo_source/horse.mp3'],
      },
      selectionList: [],
      query: {},
      box: false,
      loading: true,
      loadingChild: true,
      page: {
        pageSize: 10,
        pageSizes: [10, 30, 50, 100, 200],
        currentPage: 1,
        total: 0,
      },
      dataParent: [],
      dataChild: [],
      option: option,
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data',
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/blade-system/user/import-user',
          },
          {
            label: '数据覆盖',
            prop: 'isCovered',
            type: 'switch',
            width: 80,
            dicData: [
              {
                label: '否',
                value: 0,
              },
              {
                label: '是',
                value: 1,
              },
            ],
            value: 0,
            slot: true,
            rules: [
              {
                required: true,
                message: '请选择是否覆盖',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.dict_add, false),
        delBtn: this.validData(this.permission.dict_delete, false),
        editBtn: this.validData(this.permission.dict_edit, false),
        viewBtn: false,
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  watch: {
    'excelForm.isCovered'() {
      if (this.excelForm.isCovered !== '') {
        const column = this.findObject(this.excelOption.column, 'excelFile');
        column.action = `/blade-system/user/import-user?isCovered=${this.excelForm.isCovered}`;
      }
    },
  },
  mounted() { },
  methods: {
    rowSave(row, done, loading) {
      const form = {
        ...row,
        dictKey: -1,
      };
      add(form).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleRowClick(row) {
      this.$refs.crud.rowView(row);
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDict(this.formParent.id).then(res => {
          this.formParent = res.data.data;
        });
      }
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getParentList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(
        res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.dataParent = data.records;
          this.loading = false;
          this.selectionClear();
        }
      );
    },
    handleImport(){
      this.excelBox = true;
    },
    handleTemplate() {
      exportBlob(
        `/blade-system/user/export-template?${this.website.tokenHeader}=${getToken()}`
      ).then(res => {
        downloadXls(res.data, '导入数据模板.xlsx');
      });
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.excelBox = false;
      this.refreshChange();
      done();
    },
  },
};
</script>
